<template>
  <div style="padding: 10px">
    <!-- 修改昵称组件 -->
    <van-nav-bar title="修改昵称" left-text="取消" right-text="完成" left-arrow @click-left="onClickLeft" @click-right="onClickRight" />
    <van-field v-model="message" rows="2" autosize type="textarea" maxlength="7" placeholder="请输入新昵称" show-word-limit />
  </div>
</template>

<script>
import { updateUser } from '@/api/user'
export default {
  name: 'UpdateName',
  props: {
    user: {
      type: [Number, String, Object],
      required: true
    }
  },
  data () {
    return {
      message: ''
    }
  },
  created () {
    this.message = this.user.name
  },
  methods: {
    onClickLeft () {
      this.$emit('close')
    },
    async onClickRight () {
      try {
        if (this.message.trim() === '') return this.$toast('请输入昵称')
        await updateUser({
          name: this.message
        })
        this.$emit('close')
        this.user.name = this.message
        this.$toast('更新昵称成功')
      } catch (err) {
        console.dir(err)
        if (err.response && err.response.status === 409) {
          return this.$toast('用户名已存在')
        }
        this.$toast('更新昵称失败')
      }
    }
  }
}
</script>

<style scoped lang="less">
</style>
